#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
#define OK 1 
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct
{
    char * ch;
    int length;
}HString;
// p75 algothrim 4.4
Status StrInsert(HString &S, int pos, HString T)
{
    if (pos < 0 || pos > S.length + 1)
        return ERROR;
    if (T.length)
    {
        if (!(S.ch = (char *)realloc(S.ch, (S.length + T.length) * sizeof(char))))
            exit(OVERFLOW);
        for (int i = S.length - 1; i >= pos - 1; --i)
            S.ch[i + T.length] = S.ch[i];
        for (int i = 0; i < T.length; ++i)
            S.ch[pos - 1 + i] = T.ch[i];
        S.length += T.length;
    }
    return OK;
}
Status StrAssign(HString &T, const char * chars)
{
    if (T.ch)
        free(T.ch);
    int i = 0;
    for (char * c = (char*)chars; *c; ++c, ++i);
    if (!i)
    {
        T.ch = NULL;
        T.length = 0;
    }
    else
    {
        if (!(T.ch = (char *)malloc(i * sizeof(char))))
            exit(OVERFLOW);
        for (int j = 0; j < i; ++j)
            T.ch[j] = chars[j];
        T.length = i;
    }
    return OK;
}
int StrLength(HString S)
{
    return S.length;
}
int StrCompare(HString S, HString T)
{
    for (int i = 0; i < S.length && i < T.length; ++i)
        if (S.ch[i] != T.ch[i])
            return S.ch[i] - T.ch[i];
    return S.length - T.length;
}
Status ClearString(HString &S)
{
    if (S.ch)
        free(S.ch);
    S.length = 0;
    return OK;
}
Status Concat(HString &T, HString S1, HString S2)
{
    if (T.ch)
        free(T.ch);
    if (!(T.ch = (char *)malloc((S1.length + S2.length) * sizeof(char))))
        exit(OVERFLOW);
    for (int i = 0; i < S1.length; ++i)
        T.ch[i] = S1.ch[i];
    T.length = S1.length + S2.length;
    for (int i = S1.length; i < T.length; ++i)
        T.ch[i] = S2.ch[i - S1.length];
    return OK;
}
Status SubString(HString &Sub, HString S, int pos, int len)
{
    if (pos < 1 || pos > S.length || len < 0 || pos + len > S.length + 1)
        return ERROR;
    if (Sub.ch)
        free(Sub.ch);
    if (!len)
    {
        Sub.ch = NULL;
        Sub.length = 0;
    }
    else
    {
        Sub.ch = (char *)malloc(len * sizeof(char));
        for (int i = 0; i < len; ++i)
            Sub.ch[i] = S.ch[pos - 1 + i];
        Sub.length = len;
    }
    return OK;
}

void Show(HString T)
{
    for (int i = 0; i < T.length; ++i)
        printf("%c", T.ch[i]);
    printf("\n");
}
int main(void)
{
    HString str1, str2;
    str1.ch = str2.ch = NULL;  // 第一次使用未分配空间导致free失败
    StrAssign(str1, "helloworld");
    Show(str1);
    StrAssign(str2, " ");
    Show(str2);
    StrInsert(str1, 6, str2);
    Show(str1);
    StrAssign(str1, "he lloworld");
    Show(str1);

    

    return 0;
}